<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/28
 * Time: 14:53
 */

namespace app\admin\controller\mall;

use app\common\controller\AdminController;
use think\app;
use think\facade\Db;
use think\facade\View;

class Net extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = app('app\common\model\mall\Account');//网上课程
        $this->rtagmodel = app('app\common\model\common\RelationTag');//关联-标签中间
        $this->catemodel = app('app\common\model\common\Categories');//分类
        $this->tagmodel = app('app\common\model\common\Tags');//标签
        $this->netitemmodel = app('app\common\model\media\AccountItem');//网上课程目录
    }
    public function get_where($array = []){
        $arr[] = ['type','=',1];
        if(isset($array['category_id']) && !empty($array['category_id'])){
            $arr[] = ['category_id','=',$array['category_id']];
        }
        if(isset($array['title']) && !empty($array['title'])){
            $arr[] = ['title','like','%'.$array['title'].'%'];
        }
        return $arr;
    }

    public function get_with(){
        return 'category';
    }

    public function otherData(){


        $data = $this->catemodel->field('id,name,parent_id')->with(['childs'=>function($query){
            $query->where(['type'=>2])->with(['childs'=>function($query){
                $query->where(['type'=>2])->select();
            }]);
        }
        ])->where(['parent_id'=>0,'type'=>2])->order('sort asc')->select();

        View::assign('data',$data);
    }

    public function get_other(){


        $data = $this->catemodel->field('id,name,parent_id')->with(['childs'=>function($query){
            $query->where(['type'=>2])->with(['childs'=>function($query){
                $query->where(['type'=>2])->select();
            }]);
        }
        ])->where(['parent_id'=>0,'type'=>2])->order('sort asc')->select();

        $tag = $this->tagmodel->field('id,name')->where('type',2)->select();

        View::assign(['data'=>$data,'tags'=>$tag]);
    }

    public function add(){

        if($this->request->isPost()){

            $data = $this->request->post();

            Db::startTrans();
            try{
                if($data['pay_type'] ==0 && ($data['integral'] <= 0 || $data['price'] <=0)){
                    return json(['code'=>1,'msg'=>'价格或积分不能为空']);
                }elseif($data['pay_type'] ==1 && $data['price'] <= 0 ){
                    return json(['code'=>1,'msg'=>'价格不能为空']);

                }elseif($data['pay_type'] ==2 && $data['integral'] <= 0 ){
                    return json(['code'=>1,'msg'=>'积分不能为空']);
                };
                if(!$data['image']){
                    return json(['code'=>1,'msg'=>'请上传轮播图片']);
                }
                $data['image'] = implode(',',$data['image']);
                $data['app_id'] = $this->model->getApp();
                $articleId = $this->model->save($data);

                if(!empty($data['work']) || !empty($data['video']) || !empty($data['work']) || !empty($data['sort']) ){

                    /*获取章节数据*/
                    $item=[];
                    foreach ($data['work'] as $k=>$v){
                        $item[$k]['work'] = $v;
                        $item[$k]['sort'] = $data['sort'][$k];
                        $item[$k]['video'] = $data['video'][$k];

                        if(is_null($data['video'][$k])){
                            $item[$k]['is_can'] =0;
                        }else{
                            $item[$k]['is_can'] =1;
                        }
                        $item[$k]['article_id'] = $this->model->id;

                    }
                    $this->netitemmodel->saveAll($item);
                }else{
                    return json(['code'=>1,'msg'=>'请补全课程目录信息']);
                }
                if(!empty($data['tags'])){
                    $tags= [];
                    foreach($data['tags'] as $k=>$v){
                        $tags[$k]['other_id'] = $this->model->id;
                        $tags[$k]['type'] =2 ;
                        $tags[$k]['tag_id'] = $v;
                    }
                    $this->rtagmodel->saveAll($tags);
                }

                Db::commit();
                return json(['code'=>0,'msg'=>'添加成功']);
            }catch (\Exception $exception){
                Db::rollBack();
                return json(['code'=>1,'msg'=>'添加失败','data'=>$exception->getMessage()]);
            }

        }else{
            if(method_exists($this,'get_other')){
                $this->get_other($this->request->param() ?? []);
            }
            return view();
        }
    }

    public function edit(){

        $id = $this->request->param('id');
        if($this->request->isPost()){

            $article = $this->model->find($id);
            $data = $this->request->param();

            Db::startTrans();
            try{
                if($data['pay_type'] ==0 && ($data['integral'] <= 0 || $data['price'] <=0)){
                    return json(['code'=>1,'msg'=>'价格或积分不能为空']);
                }elseif($data['pay_type'] ==1 && $data['price'] <= 0 ){

                    return json(['code'=>1,'msg'=>'价格不能为空']);

                }elseif($data['pay_type'] ==2 && $data['integral'] <= 0 ){

                    return json(['code'=>1,'msg'=>'积分不能为空']);
                };

                if(!$data['image']){
                    return json(['code'=>1,'msg'=>'请上传轮播图片']);
                }
                $data['image']=implode(',',$data['image']);

                $article->save($data);
                /*获取章节数据*/
                if(!empty($data['work']) || !empty($data['video']) || !empty($data['work']) || !empty($data['sort']) ){
                    $item=[];
                    //先删除不存在attr_id之中的sku
                    if(!empty($data['attr_id'])){
                        $this->netitemmodel->whereNotIn('id',$data['attr_id'])->where('article_id',$article['id'])->delete();
                    }
                    foreach ($data['work'] as $k=>$v){
                        $item[$k]['work'] = $v;
                        $item[$k]['sort'] = $data['sort'][$k];
                        $item[$k]['video'] = $data['video'][$k];

                        $item[$k]['article_id'] = $article->id;
                        if(is_null($data['video'][$k])){
                            $item[$k]['is_can'] =0;
                        }else{
                            $item[$k]['is_can'] =1;
                        }

                        if(isset($data['attr_id'][$k])){

                            $this->netitemmodel->where('id',$data['attr_id'][$k])->update($item[$k]);
                        }else{
                            $this->netitemmodel->save($item[$k]);
                        }
                    }

                }else{
                    return json(['code'=>1,'msg'=>'请补全课程目录信息']);
                }

                $del = $this->rtagmodel->where('other_id',$id)->select();
                $del->delete();
                if(!empty($data['tags'])){
                    $tags= [];
                    foreach($data['tags'] as $k=>$v){
                        $tags[$k]['other_id'] = $id;
                        $tags[$k]['type'] =2 ;
                        $tags[$k]['tag_id'] = $v;
                    }
                    $this->rtagmodel->saveAll($tags);
                }

                Db::Commit();
                return json(['code'=>0,'msg'=>'更新成功']);
            }catch (\Exception $exception){
                Db::rollBack();
                return json(['code'=>1,'msg'=>'更新失败','data'=>$exception->getMessage()]);
            }


        }else{

            $article = $this->model->with(['items','tags'])->find($id);

            $article['tags'] = $this->rtagmodel->where(['other_id'=>$article['id'],'type'=>2])->column('tag_id');

            if(method_exists($this,'get_other')){
                $this->get_other($this->request->param() ?? []);
            }


            return View('',['row'=>$article]);
        }
    }

    public function action(){

        $param= $this->request->param();

        try{
            $row = $this->model->where('id',$param['id'])->find();
            $row->save($param);

        }catch (\Exception $exception){
            return json(['code'=>1,'msg'=>$exception->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {

        $advertmodel = app('app\common\model\banner\Advert');//广告
        $row = $this->model->whereIn('id', $id)->select();
        $rtag = $this->rtagmodel->where('other_id',$id)->select();
        $rtagitem = $this->netitemmodel->where('article_id',$id)->select();
        empty($row) && $this->error('数据不存在');
        $advert = $advertmodel->where(['type'=>3,'bind_id'=>$id])->find();
        if(!empty($advert)){$this->error('此网上课程已绑定广告，请解绑后在删除');}
        try {
            $save = $row->delete();
            $rtag->delete();
            $rtagitem->delete();

        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }
}